myApp.controller('login', ['$scope', '$location', '$http', '$shop', '$employee', function($scope, $location, $http, $shop, $employee){

	$scope.userName = "";
	$scope.password = "";
	$scope.shopId = "";
	$scope.allShop = [];
	$scope.position = "";

	(function() {
		$http.get('searchAllShop').then(function successCallback(response) {
			
			$scope.allShop = response.data;

		}, function errorCallback(response) {
			console.log("fail：" + response);
		});		
	})();

	$scope.login = function() {

		if($scope.userName === "") {
			alert("请填写用户名！");
			return;
		}
		if($scope.password === "") {
			alert("请填写密码！");
			return;
		}
		if(($scope.shopId === "" || $scope.shopId === null) && $scope.position == "0")  {
			alert("请选择店铺！");
			return;
		}
		if($scope.position === "" || $scope.position === null) {
			alert("请选择职位！");
			return;
		}

		if($scope.position == "0") {
			
			var data = {
				"employee.userName": $scope.userName,
				"employee.password": $scope.password,
				"employee.shopId": $scope.shopId
			};

			var postCfg = {
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				transformRequest: function (data) {
					return $.param(data);
				}
			};

			$http.post('authenticateEmployee', data, postCfg).then(function successCallback(response) {
				if(response.data[0].userName === $scope.userName) {
					$employee.currentEmployee = response.data[0];
					$shop.loadShop($scope.shopId, $scope.allShop);
					$location.path('/home');
				}else {
					alert("用户名或密码有误！");
					$scope.userName = "";
					$scope.password = "";
					$scope.shopId = "";
					$scope.position = "";
				}

				console.log("ok：" + response);
			}, function errorCallback(response) {
				alert("登录操作失败!");
				console.log("fail：" + response);
			});
		}else {
			var data = {
				"employee.userName": $scope.userName,
				"employee.password": $scope.password,
			};

			var postCfg = {
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				transformRequest: function (data) {
					return $.param(data);
				}
			};

			$http.post('authenticateAdmin', data, postCfg).then(function successCallback(response) {
				if(response.data[0].userName === $scope.userName) {
					$employee.currentEmployee = response.data[0];
					$location.path('/home');
				}else {
					alert("用户名或密码有误！");
					$scope.userName = "";
					$scope.password = "";
					$scope.shopId = "";
					$scope.position = "";
				}

				console.log("ok：" + response);
			}, function errorCallback(response) {
				alert("登录操作失败!");
				console.log("fail：" + response);
			});
		}

	}

}]);